<template>
  <div class="reserve-course-page">
    <div class="header">
      <h2>预约课程</h2>
    </div>

    <!-- 筛选条件 -->
    <div class="filters">
      <div class="filter-row">
        <div class="filter-item">
          <div class="filter-label">课程类型:</div>
          <el-select
              v-model="courseTypeFilter"
              placeholder="请选择课程类型"
              clearable
              class="filter-select"
              size="small"
          >
            <el-option label="全部类型" value=""></el-option>
            <el-option
                v-for="courseType in courseTypes"
                :key="courseType"
                :label="courseType"
                :value="courseType">
            </el-option>
          </el-select>
        </div>

        <div class="filter-item">
          <div class="filter-label">上课日期:</div>
          <el-date-picker
              v-model="classDateFilter"
              type="date"
              placeholder="请选择上课日期"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              class="filter-select"
              size="small"
          />
        </div>
      </div>

      <div class="filter-actions">
        <el-button type="primary" @click="applyFilters" size="small">筛选</el-button>
        <el-button @click="resetFilters" size="small">重置</el-button>
      </div>
    </div>

    <!-- 课程列表 -->
    <div class="course-list">
      <div
          v-for="course in filteredCourses"
          :key="course.id"
          class="course-card"
          @click="showCourseDetail(course)"
      >
        <div class="course-header">
          <div class="course-name">{{ course.name }}</div>
          <div class="coach-name">{{ course.coach?.name || '未知教练' }}</div>
        </div>

        <div class="course-details">
          <div class="detail-item">
            <i class="el-icon-time"></i>
            <span>{{ formatDateTime(course.time) }}</span>
          </div>
          <div class="detail-item">
            <i class="el-icon-location"></i>
            <span>{{ course.room }}</span>
          </div>
        </div>

        <div class="reservation-info">
          <div class="progress-container">
            <el-progress
                :percentage="(course.currentCount / course.maxCount) * 100"
                :show-text="false"
                :stroke-width="8"
                :status="course.currentCount >= course.maxCount ? 'exception' : ''"
            />
          </div>
          <div class="reservation-text">
            已预约: {{ course.currentCount }} / {{ course.maxCount }}
          </div>
        </div>

        <div class="action-button">
          <el-button
              type="primary"
              size="small"
              :disabled="course.currentCount >= course.maxCount"
              @click.stop="reserveCourse(course)"
              round
          >
            立即预约
          </el-button>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="filteredCourses.length === 0" class="empty-state">
      <i class="el-icon-folder-open" style="font-size: 48px; color: #c0c4cc;"></i>
      <p>暂无符合条件的课程</p>
    </div>

    <!-- 课程详情弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        :title="selectedCourse?.name || '课程详情'"
        width="95%"
        class="course-dialog"
    >
      <div class="course-detail" v-if="selectedCourse">
        <div class="detail-section">
          <div class="detail-item large">
            <i class="el-icon-user"></i>
            <div>
              <div class="label">教练</div>
              <div class="value">{{ selectedCourse.coach?.name || '未知教练' }}</div>
            </div>
          </div>

          <div class="detail-item large">
            <i class="el-icon-time"></i>
            <div>
              <div class="label">上课时间</div>
              <div class="value">{{ formatDateTime(selectedCourse.time) }}</div>
            </div>
          </div>

          <div class="detail-item large">
            <i class="el-icon-location"></i>
            <div>
              <div class="label">上课地点</div>
              <div class="value">{{ selectedCourse.room }}</div>
            </div>
          </div>

          <div class="detail-item large">
            <i class="el-icon-user"></i>
            <div>
              <div class="label">预约情况</div>
              <div class="value reservation-status">
                <el-progress
                    :percentage="(selectedCourse.currentCount / selectedCourse.maxCount) * 100"
                    :stroke-width="16"
                    :show-text="true"
                    :status="selectedCourse.currentCount >= selectedCourse.maxCount ? 'exception' : ''"
                />
                <div>{{ selectedCourse.currentCount }} / {{ selectedCourse.maxCount }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" round>关闭</el-button>
          <el-button
              type="primary"
              :disabled="selectedCourse?.currentCount >= selectedCourse?.maxCount"
              @click="reserveCourse(selectedCourse)"
              round
          >
            立即预约
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/utils/api.js'

// 筛选条件
const courseTypeFilter = ref('')
const classDateFilter = ref('')

// 弹窗可见性
const dialogVisible = ref(false)

// 选中的课程
const selectedCourse = ref(null)

// 课程列表数据（从后端获取）
const courses = ref([])

// 课程类型列表
const courseTypes = ref([])

// 用户预约记录
// const userReservations = ref([])

// 获取课程列表数据
const fetchCourseList = async () => {
  try {
    const response = await api({
      url: '/reserveCourse',
      method: 'get'
    })

    if (response.success) {
      courses.value = response.data
    } else {
      ElMessage.error('获取课程列表失败')
    }
  } catch (error) {
    console.error('获取课程列表失败:', error)
    ElMessage.error('获取课程列表失败: ' + (error.message || '未知错误'))
  }
}

// 获取课程类型列表
const fetchCourseTypes = async () => {
  try {
    const response = await api({
      url: '/reserveCourse/courseList',
      method: 'get'
    })

    if (response.success) {
      courseTypes.value = response.data
    } else {
      ElMessage.error('获取课程类型列表失败')
    }
  } catch (error) {
    console.error('获取课程类型列表失败:', error)
    ElMessage.error('获取课程类型列表失败: ' + (error.message || '未知错误'))
  }
}

// 筛选后的课程列表
const filteredCourses = computed(() => {
  let result = courses.value

  // 按课程类型筛选
  if (courseTypeFilter.value) {
    result = result.filter(course => course.name.includes(courseTypeFilter.value))
  }

  // 按上课日期筛选
  if (classDateFilter.value) {
    result = result.filter(course => {
      const courseDate = course.time.split('T')[0]
      return courseDate === classDateFilter.value
    })
  }

  return result
})

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}\n${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 应用筛选条件
const applyFilters = () => {
  // 筛选会自动应用，无需额外操作
}

// 重置筛选条件
const resetFilters = () => {
  courseTypeFilter.value = ''
  classDateFilter.value = ''
}

// 显示课程详情
const showCourseDetail = (course) => {
  selectedCourse.value = course
  dialogVisible.value = true
}

// 预约课程
const reserveCourse = async (course) => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
        `确定要预约课程 "${course.name}" 吗？`,
        '确认预约',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const response = await api({
      url: '/reserveCourse/reserve',
      method: 'put',
      data: {
        courseId: course.id
      }
    })

    if (response.success) {
      // 更新本地数据状态
      course.currentCount++

      // 如果在详情弹窗中也有相同课程，同步更新
      if (selectedCourse.value && selectedCourse.value.id === course.id) {
        selectedCourse.value.currentCount++
      }

      ElMessage.success('预约成功')

      // 如果在弹窗中预约，关闭弹窗
      if (dialogVisible.value) {
        dialogVisible.value = false
      }
    } else {
      ElMessage.error(response.message || '预约失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('预约失败: ' + (error.message || '未知错误'))
    }
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCourseList()
  fetchCourseTypes()
})
</script>

<style scoped>
.reserve-course-page {
  padding: 12px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 15px;
  padding: 12px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 6px rgba(0,0,0,0.1);
}

.header h2 {
  margin: 0;
  color: #333;
  font-size: 20px;
}

.filters {
  margin-bottom: 15px;
  padding: 12px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 6px rgba(0,0,0,0.1);
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 12px;
}

.filter-item {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 140px;
}

.filter-label {
  margin-right: 8px;
  font-weight: 500;
  white-space: nowrap;
  font-size: 14px;
  color: #666;
}

.filter-select {
  flex: 1;
}

.filter-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.course-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 15px;
}

.course-card {
  background-color: white;
  border-radius: 12px;
  padding: 15px;
  box-shadow: 0 2px 6px rgba(0,0,0,0.1);
  transition: all 0.3s ease;
}

.course-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.course-header {
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
  margin-bottom: 12px;
}

.course-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.coach-name {
  font-size: 14px;
  color: #666;
}

.course-details {
  margin-bottom: 15px;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.detail-item i {
  margin-right: 8px;
  color: #409eff;
}

.reservation-info {
  margin-bottom: 15px;
}

.progress-container {
  margin-bottom: 8px;
}

.reservation-text {
  font-size: 14px;
  color: #666;
  text-align: right;
}

.action-button {
  display: flex;
  justify-content: center;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 6px rgba(0,0,0,0.1);
}

.empty-state p {
  margin-top: 15px;
  color: #999;
  font-size: 16px;
}

.course-dialog :deep(.el-dialog) {
  border-radius: 16px;
  margin-top: 5vh !important;
}

.course-detail {
  padding: 10px 0;
}

.detail-section {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.detail-item.large {
  display: flex;
  align-items: flex-start;
}

.detail-item.large i {
  font-size: 18px;
  margin-top: 2px;
}

.detail-item.large > div {
  flex: 1;
  margin-left: 10px;
}

.label {
  font-size: 14px;
  color: #999;
  margin-bottom: 4px;
}

.value {
  font-size: 16px;
  color: #333;
}

.reservation-status {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  padding: 0 10px 10px;
}

.dialog-footer :deep(.el-button) {
  flex: 1;
  margin: 0 5px;
}

/* iPhone 15 Pro Max 等大屏手机适配 */
@media (min-width: 430px) {
  .reserve-course-page {
    padding: 15px;
  }

  .header {
    padding: 15px;
  }

  .filters {
    padding: 15px;
  }

  .filter-row {
    gap: 15px;
    margin-bottom: 15px;
  }

  .course-card {
    padding: 20px;
  }

  .course-name {
    font-size: 20px;
  }
}

/* 小屏手机适配 */
@media (max-width: 370px) {
  .filter-item {
    min-width: 100%;
  }

  .filter-label {
    width: 60px;
  }

  .course-name {
    font-size: 16px;
  }

  .detail-item {
    font-size: 13px;
  }
}
</style>
